//
//  YXTaskListTableViewController.m
//  MockProject
//
//  Created by 周丽丽 on 16/8/23.
//  Copyright © 2016年 niuzhaowang. All rights reserved.
//
#import "YXTaskListTableViewController.h"
#import "YXtaskListTableViewCell.h"
#import "YXDownloadManagementViewController.h"
#import "YXTaskListModel.h"
#import "YXDownloader.h"
#import "YXDownloadManger.h"
#import "DownloaderEntity.h"
@interface YXTaskListTableViewController ()
@property (nonatomic, strong) NSMutableArray *downloadersArr;
@property (nonatomic, strong) NSMutableArray *readDownloadersArr;
@property (nonatomic, strong) NSMutableArray *saveDownloadersArr;
@property (nonatomic, strong) YXDownloadManger *manger;
@property (nonatomic, strong) UILabel *noTaskLabel;
@end
@implementation YXTaskListTableViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kMaxDownloadCountChanged object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"";
    self.navigationItem.title = @"任务列表";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self setupManger];
    [self setupRightBarbutton];
    [self setupNoTaskLabel];
    self.downloadersArr = [NSMutableArray array];
    self.readDownloadersArr = [NSMutableArray array];
    self.saveDownloadersArr = [NSMutableArray array];
    [self readDownloadersArrFromPList];
    [self loadDownloader];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(maxDownloadCountChangedSelector:) name:kMaxDownloadCountChanged object:nil];
}
- (void)maxDownloadCountChangedSelector:(NSNotification *)noti{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    NSInteger maxDownloadCountValue = [defaults integerForKey:kMaxDownloadCount];
    self.manger.maxDownloadCountValue = maxDownloadCountValue;
}
- (void)setupManger{
    self.manger = [YXDownloadManger sharedInstance];
    __weak typeof(self)weakSelf = self;
    self.manger.downloaderCompleteBlockForTaskListVC = ^(){
        [weakSelf judgeWhetherNoTaskLabelISDisplayed];
        [weakSelf.tableView reloadData];
    };
    self.manger.saveDownloaderBlock = ^(){
        [weakSelf saveDownloader];
    };
}
#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    [self judgeWhetherNoTaskLabelISDisplayed];
    return self.downloadersArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *taskListCellID = @"taskListCellID";
    YXtaskListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:taskListCellID];
    if (!cell) {
        cell = [[YXtaskListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:taskListCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.downloader = self.downloadersArr[indexPath.row];
    cell.downloadButtonClickBlock = ^(YXtaskListTableViewCell *cell){
        [self.downloadersArr removeObject:cell.downloader];
        [self.manger addDownloader:cell.downloader];
        [self.tableView reloadData];
    };
    return cell;
}
#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80 * AutoSizeScaleX;
}
- (void)setupNoTaskLabel{
    UILabel *label = [[UILabel alloc]init];
    label.text = @"任务为空哦";
    label.textColor = [UIColor colorWithHexString:@"ff7000"];
    [self.view addSubview:label];
    self.noTaskLabel = label;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-50);
        make.centerX.equalTo(self.view);
    }];
    [self judgeWhetherNoTaskLabelISDisplayed];
}
- (void)judgeWhetherNoTaskLabelISDisplayed{
    if (self.downloadersArr.count == 0) {
        self.noTaskLabel.hidden = NO;
    }else if(self.downloadersArr.count > 0){
        self.noTaskLabel.hidden = YES;
    }
}
- (void)setupRightBarbutton{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.bounds = CGRectMake(0, 0, 90, 27);
    button.x = ([UIScreen mainScreen].bounds.size.width - button.width - 15)* 0.5;
    button.adjustsImageWhenHighlighted = NO;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithHexString:@"bf390c"] forState:UIControlStateHighlighted];
    [button setTitle:@"下载管理" forState:UIControlStateNormal];
    [button setTitle:@"下载管理" forState:UIControlStateHighlighted];
    [button setImage:[[UIImage imageNamed:@"下载管理icon正常态"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button setImage:[[UIImage imageNamed:@"下载管理icon点击态"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateHighlighted];
    button.layer.cornerRadius = 13.5;
    button.layer.borderColor = [UIColor whiteColor].CGColor;
    button.layer.borderWidth = 1;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(downloadManagementButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(changeBorderColor:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = item;
}
- (void)downloadManagementButtonClick:(UIButton *)sender{
    self.hidesBottomBarWhenPushed=YES;
    YXDownloadManagementViewController *downloadManagementVc = [[YXDownloadManagementViewController alloc]init];
    [self.navigationController pushViewController:downloadManagementVc animated:YES];
    self.hidesBottomBarWhenPushed=NO;
    sender.layer.borderColor = [UIColor whiteColor].CGColor;
}
- (void)changeBorderColor:(UIButton *)sender{
    sender.layer.borderColor = [UIColor colorWithHexString:@"bf390c"].CGColor;
}
- (void)readDownloadersArrFromPList{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TaskList.plist" ofType:nil]];
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
    for (NSDictionary *dict in array) {
        [arrayM addObject:[[YXTaskListModel alloc]initWithDictionary:dict error:nil]];
    }
    for (NSInteger i = 0; i < arrayM.count; i++) {
        YXDownloader *downloader = [YXDownloader downloader];
        downloader.taskModel = arrayM[i];
        [self.readDownloadersArr  addObject:downloader];
    }
}
- (void)saveDownloader{
    [MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
        [self.downloadersArr enumerateObjectsUsingBlock:^(YXDownloader *  _Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
            DownloaderEntity *entity = [DownloaderEntity MR_createEntityInContext:localContext];
            entity.content = [downloader toJSONString];
            entity.urlStr = downloader.urlStr;
            [self.saveDownloadersArr addObject:downloader];
        }];
    }];
}
- (void)loadDownloader{
    NSArray *arr = [DownloaderEntity MR_findAll];
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:arr.count];
    [arr enumerateObjectsUsingBlock:^(DownloaderEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        JSONModelError *error = nil;
        YXDownloader *downloader = [[YXDownloader alloc]initWithString:obj.content error:&error];
        [arrM addObject:downloader];
    }];
    [self.readDownloadersArr enumerateObjectsUsingBlock:^(YXDownloader *_Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *urlString = downloader.urlStr;
        NSArray *urlArr = [DownloaderEntity MR_findByAttribute:@"urlStr" withValue:urlString];
        if (urlArr.count == 0) {
            [arrM addObject:downloader];
        }
    }];
    [arrM enumerateObjectsUsingBlock:^(YXDownloader *_Nonnull downloader, NSUInteger idx, BOOL * _Nonnull stop) {
        if (downloader.state == TaskStateNotStart){
            [self.downloadersArr addObject:downloader];
        }
    }];
}
@end
